<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="平台资源管理" data-page-identification="u_ropfsxsox9">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_0w16f155sd 自定义模板_gbg5bo7rfs -->
            <div class="resource-div">
                <div class="radio-body">
                    <a-radio-group
                        v-model:value="state.radioValue"
                        button-style="solid"
                        style="margin-bottom: 16px"
                        @change="getData"
                    >
                        <a-radio-button value="人力资源">人力资源</a-radio-button>
                        <a-radio-button value="其他资源">其他资源</a-radio-button>
                    </a-radio-group>
                    <div class="radio-btn">
                        <a-button
                            v-if="state.radioValue === '其他资源'"
                            @click="handleAdd"
                            type="primary"
                            v-permission="'50001252_vid_ee9u5vbgni'"
                            >新建</a-button
                        >
                    </div>
                </div>
                <template v-if="state.radioValue === '人力资源'">
                    <div class="top-search">
                        <a-row :gutter="16">
                            <a-col :span="6">
                                <a-form-item label="日期" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
                                    <a-range-picker
                                        v-model:value="state.filter.month"
                                        value-format="YYYY-MM-DD"
                                        @change="getData"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-form-item label="迭代项目" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                                    <a-select
                                        :options="state.projectList"
                                        v-model:value="state.filter.projectName"
                                        placeholder="请选择"
                                        @change="getData"
                                        mode="multiple"
                                        allowClear
                                        show-search
                                        @focus="getProjectList"
                                        :filter-option="
                                            (input, option) => {
                                                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="6">
                                <a-button type="primary" ghost @click="resetData">重置</a-button>
                            </a-col>
                        </a-row>
                    </div>
                    <div class="people-content">
                        <div class="table-box">
                            <a-table
                                :data-source="state.peopleTableData"
                                :columns="peopleColumns"
                                :loading="state.peopleTableLoading"
                                bordered
                                :pagination="false"
                                :scroll="{ y: state.tableHeight }"
                            >
                                <template #bodyCell="{ column, record }">
                                    <template v-if="column.dataIndex === 'workHours'">
                                        <span style="cursor: pointer; color: #3875ff" @click="getWorkHour(record)">{{
                                            record.workHours
                                        }}</span>
                                    </template>
                                </template>
                            </a-table>
                        </div>
                        <div class="table-box">
                            <a-table
                                :data-source="state.workHourTableData"
                                :columns="workHourColumns"
                                :loading="state.workHourTableLoading"
                                bordered
                                :pagination="false"
                                :scroll="{ y: state.tableHeight }"
                        /></div>
                    </div>
                </template>
                <template v-else>
                    <div class="table-box">
                        <a-table
                            :data-source="state.otherTableData"
                            :columns="otherColumns"
                            :row-key="record => record.id"
                            bordered
                            :loading="state.otherTableLoading"
                            :pagination="false"
                            :scroll="{ y: state.tableHeight + 50 }"
                        >
                            <template #bodyCell="{ column, record, index }">
                                <!-- 资产类别 -->
                                <template v-if="column.dataIndex === 'assetType'">
                                    <a-select
                                        v-if="record.editing"
                                        v-model:value="record.assetType"
                                        placeholder="请选择"
                                        :options="state.assetClassList"
                                        style="width: 100%"
                                        show-search
                                        :filter-option="
                                            (input, option) => {
                                                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                    />
                                    <span v-else>{{ record.assetType }}</span>
                                </template>

                                <!-- 资产名称 -->
                                <template v-else-if="column.dataIndex === 'assetName'">
                                    <a-input
                                        v-if="record.editing"
                                        v-model:value="record.assetName"
                                        placeholder="请输入"
                                    />
                                    <span v-else>{{ record.assetName }}</span>
                                </template>

                                <!-- 资产编号 -->
                                <template v-else-if="column.dataIndex === 'assetNumber'">
                                    <a-input
                                        v-if="record.editing"
                                        v-model:value="record.assetNumber"
                                        placeholder="请输入"
                                    />
                                    <span v-else>{{ record.assetNumber }}</span>
                                </template>

                                <!-- 规格型号 -->
                                <template v-else-if="column.dataIndex === 'specificationModel'">
                                    <a-input
                                        v-if="record.editing"
                                        v-model:value="record.specificationModel"
                                        placeholder="请输入"
                                    />
                                    <span v-else>{{ record.specificationModel }}</span>
                                </template>

                                <!-- 分配数量 -->
                                <template v-else-if="column.dataIndex === 'allocatedQuantity'">
                                    <a-input-number
                                        min="0"
                                        :precision="0"
                                        v-if="record.editing"
                                        v-model:value="record.allocatedQuantity"
                                        placeholder="请输入"
                                    />
                                    <span v-else>{{ record.allocatedQuantity }}</span>
                                </template>

                                <!-- 开始使用时间 -->
                                <template v-else-if="column.dataIndex === 'startTime'">
                                    <a-date-picker
                                        v-if="record.editing"
                                        value-format="YYYY-MM-DD"
                                        v-model:value="record.startTime"
                                        style="width: 100%"
                                    />
                                    <span v-else>{{ record.startTime }}</span>
                                </template>

                                <!-- 结束使用时间 -->
                                <template v-else-if="column.dataIndex === 'endTime'">
                                    <a-date-picker
                                        v-if="record.editing"
                                        value-format="YYYY-MM-DD"
                                        v-model:value="record.endTime"
                                        style="width: 100%"
                                    />
                                    <span v-else>{{ record.endTime }}</span>
                                </template>

                                <!-- 使用负责人 -->
                                <template v-else-if="column.dataIndex === 'ownerList'">
                                    <a-select
                                        v-if="record.editing"
                                        v-model:value="record.ownerList"
                                        placeholder="请选择"
                                        style="width: 100%"
                                        mode="multiple"
                                        :options="peopleList"
                                        :allowClear="true"
                                        :dropdownMatchSelectWidth="true"
                                        :showSearch="true"
                                        :filterOption="
                                            (input, option) => {
                                                return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            }
                                        "
                                        :fieldNames="{
                                            label: 'name',
                                            value: 'name'
                                        }"
                                    />
                                    <span v-else>{{ record.owner }}</span>
                                </template>

                                <!-- 操作 -->
                                <template v-else-if="column.dataIndex === 'operation'">
                                    <a-space>
                                        <a-button
                                            v-if="record.editing"
                                            type="link"
                                            size="small"
                                            :loading="record.okBtnLoading"
                                            @click="handleSave(record)"
                                            >完成</a-button
                                        >
                                        <a-button
                                            v-if="record.editing"
                                            type="link"
                                            size="small"
                                            @click="handleCancel(record, index)"
                                            >取消</a-button
                                        >
                                        <a-button
                                            v-if="!record.editing"
                                            type="link"
                                            size="small"
                                            @click="handleEdit(record)"
                                            v-permission="'50001252_vid_lp2ges9jnq'"
                                        >
                                            编辑
                                        </a-button>
                                        <a-popconfirm title="确认删除该行吗？" @confirm="handleDelete(record.id)">
                                            <a-button
                                                v-if="!record.editing"
                                                type="link"
                                                size="small"
                                                v-permission="'50001252_vid_2d8k56kxj8'"
                                            >
                                                删除
                                            </a-button>
                                        </a-popconfirm>
                                    </a-space>
                                </template>
                            </template>
                        </a-table>
                    </div>
                </template>
            </div>
            <!-- end vid_0w16f155sd 自定义模板_gbg5bo7rfs -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'useProjectId': {
            type: [String, Number],
            default: undefined
        },
        activeKey: String,
        refreshCount: Number
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    function checkRequired(value, msg = '必填项缺失') {
        if (value === undefined || value === null || value === '') {
            message.warning(msg) // 这里用 Antd 的 message，也可以改成 console.error 或 throw Error
            return false
        }
        return true
    }
    const state = reactive({
        radioValue: '人力资源',
        peopleTableLoading: false,
        otherTableLoading: false,
        workHourTableLoading: false,
        peopleTableData: [],
        workHourTableData: [],
        otherTableData: [],
        filter: {
            month: undefined,
            projectName: []
        },
        projectList: [],
        //   资产类别
        assetClassList: [],
        tableHeight: 600
    })
    const headerOffset = ref(150)
    const calcTableHeight = () => {
        state.tableHeight = window.innerHeight - 180 - headerOffset.value
    }
    onMounted(() => {
        getPlist()
        getZclb()
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })
    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
    function getZclb() {
        get('/solution-ppm-basic-data/api/v1/dictionary/search/CYXM.ZCLB').then(data => {
            state.assetClassList = data.data.map(item => {
                return {
                    label: item.itemName,
                    value: item.itemName
                }
            })
        })
    }
    const peopleColumns = ref([
        {
            dataIndex: 'role',
            title: '角色',
            ellipsis: true,
            align: 'center',
            width: 150
        },
        {
            dataIndex: 'workHours',
            title: '人天',
            ellipsis: true,
            align: 'center'
        }
    ])
    const workHourColumns = ref([
        {
            dataIndex: 'position',
            title: '岗位',
            ellipsis: true,
            align: 'center',
            width: 100,
            customCell: ({ rowSpan }) => {
                return {
                    rowSpan: rowSpan
                }
            }
        },
        {
            dataIndex: 'userName',
            title: '员工',
            ellipsis: true,
            width: 100,
            align: 'center'
        },
        {
            dataIndex: 'workHours',
            title: '人天',
            ellipsis: true,
            align: 'center'
        }
    ])
    const otherColumns = ref([
        {
            title: '序号',
            dataIndex: 'index',
            customRender: ({ index }) => index + 1,
            width: 60,
            align: 'center'
        },
        { title: '资产类别', dataIndex: 'assetType', ellipsis: true, width: 180, align: 'center' },
        { title: '资产编号', dataIndex: 'assetNumber', ellipsis: true, align: 'center' },
        { title: '资产名称', dataIndex: 'assetName', ellipsis: true, align: 'center' },
        { title: '规格型号', dataIndex: 'specificationModel', ellipsis: true, align: 'center' },
        { title: '分配数量', dataIndex: 'allocatedQuantity', ellipsis: true, align: 'center' },
        { title: '开始使用时间', dataIndex: 'startTime', ellipsis: true, align: 'center' },
        { title: '结束使用时间', dataIndex: 'endTime', ellipsis: true, align: 'center' },
        { title: '使用负责人', dataIndex: 'ownerList', ellipsis: true, align: 'center' },
        { title: '操作', dataIndex: 'operation', ellipsis: true, width: 150, align: 'center' }
    ])
    watch(
        () => [props.useProjectId, props.activeKey, props.refreshCount],
        val => {
            getData()
        },
        { immediate: true }
    )
    const peopleList = ref([])
    function getPlist() {
        get('/solution-ppm/api/v2/built-in-system-ppm/pmgf/get/allUser').then(data => {
            if (data.code === 200) {
                peopleList.value = data.data.userDtoList
            } else {
                message.error('获取用户列表失败！')
            }
        })
    }
    function getData() {
        if (!checkRequired(props.useProjectId, '请选择产品')) return
        if (state.radioValue === '人力资源') {
            getPeopleResource()
        } else {
            getOtherResource()
        }
    }
    function getWorkHour(record) {
        state.workHourTableLoading = true
        state.workHourTableData = groupData(record.childList)
        state.workHourTableLoading = false
    }
    function groupData(data) {
        let position = ''
        if (!data || !data.length) {
            return []
        }
        return data.map((item, index) => {
            if (position !== item.position) {
                position = item.position
                let rowSpan = 0
                for (let i = 0; i < data.length; i++) {
                    if (i >= index) {
                        if (position === data[i].position) {
                            rowSpan += 1
                        } else {
                            break
                        }
                    }
                }
                item.rowSpan = rowSpan
                item.border = index
            } else {
                item.rowSpan = 0
            }
            item.rowIndex = index
            return item
        })
    }
    function resetData() {
        state.filter = {
            month: [],
            projectName: []
        }
        getData()
    }
    function getProjectList() {
        get(`/solution-ppm/api/v2/built-in-system-ppm/platform_product/child_project/${props.useProjectId}`).then(
            data => {
                state.projectList = data.data.map(item => {
                    return {
                        label: item.projectName,
                        value: item.projectId
                    }
                })
            }
        )
    }

    function getPeopleResource() {
        state.peopleTableLoading = true
        state.workHourTableLoading = true
        post('/solution-ppm/api/v2/built-in-system-ppm/project_resource/human_resource', {
            projectId: props.useProjectId,
            projectIdList: state.filter.projectName,
            timeList: state.filter.month
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    state.peopleTableData = []
                    return
                }
                state.peopleTableData = data.data.roleWorkHoursList
                state.workHourTableData = groupData(data.data.userWorkHoursList)
            })
            .finally(() => {
                state.peopleTableLoading = false
                state.workHourTableLoading = false
            })
    }
    function getOtherResource() {
        state.otherTableLoading = true
        post(`/solution-ppm/api/v2/built-in-system-ppm/project_resource/search`, {
            projectId: props.useProjectId
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    state.otherTableData = []
                    return
                }
                state.otherTableData = data.data
            })
            .finally(() => {
                state.otherTableLoading = false
            })
    }
    // 新增
    const handleAdd = () => {
        if (!checkRequired(props.useProjectId, '请选择产品')) return
        state.otherTableData.push({
            assetType: undefined,
            assetNumber: '',
            assetName: '',
            specificationModel: '',
            allocatedQuantity: '',
            startTime: '',
            endTime: '',
            ownerList: undefined,
            editing: true,
            isNew: true
        })
    }

    const editData = ref({})
    // 保存
    const handleSave = record => {
        const missingFields = []

        if (!record.assetType) missingFields.push('资产类别')
        if (!record.assetName) missingFields.push('资产名称')
        if (!record.ownerList || record.ownerList.length === 0) missingFields.push('使用负责人')

        if (missingFields.length > 0) {
            message.error(`请输入或选择${missingFields.join('、')} ！`)
            return
        }
        editData.value = cloneDeep(record)
        record.okBtnLoading = true
        const api = editData.value.isNew ? post : put

        api('/solution-ppm/api/v2/built-in-system-ppm/project_resource', {
            ...editData.value,
            projectId: props.useProjectId
        })
            .then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                message.success(data.message)

                if (editData.value.isNew) {
                    // 新建数据的情况
                    const index = state.otherTableData.findIndex(item => item === record)
                    if (index !== -1) {
                        // 用后端返回的数据替换临时数据
                        state.otherTableData.splice(index, 1, {
                            ...data.data,
                            editing: false
                        })
                    }
                } else {
                    // 编辑现有数据的情况
                    Object.assign(record, data.data, { editing: false })
                }
                record.editing = false
            })
            .finally(() => {
                editData.value = {}
                record.okBtnLoading = false
            })
    }

    // 编辑
    const handleEdit = record => {
        record.editing = true
    }

    // 取消
    const handleCancel = (record, index) => {
        if (!record.id) {
            console.log(index)
            state.otherTableData = state.otherTableData.filter(item => item.id !== record.id)
        } else {
            record.editing = false
        }
    }

    // 删除
    const handleDelete = id => {
        del(`/solution-ppm/api/v2/built-in-system-ppm/project_resource/${id}`).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            getData()
        })
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    /*样式*/
    .people-content {
        display: flex;
        gap: 16px;
        justify-content: space-between;
        .table-box {
            flex: 1;
        }
    }
    .radio-body {
        position: relative;
    }
    .radio-btn {
        position: absolute;
        right: 0;
        top: 0;
    }
    .table-box :deep(.@{ant-prefix}-table-tbody) tr > td {
        font-size: 14px;
        font-weight: 400;
        color: #262626;
        border-bottom: 1px solid #d9d9d9;
        padding: 8px 16px;
        word-break: break-all;
    }
</style>
